// pages/job-applicants/job-applicants.js
Page({
  data: {
    jobId: null,
    jobInfo: null,
    applicants: [],
    loading: false,
    hasMore: true,
    page: 0,
    size: 10,
    activeTab: 0,
    tabs: [
      { key: '', label: '全部' },
      { key: 'PENDING', label: '待处理' },
      { key: 'APPROVED', label: '已通过' },
      { key: 'REJECTED', label: '已拒绝' }
    ]
  },

  onLoad(options) {
    if (options.jobId) {
      this.setData({ jobId: options.jobId });
      this.checkLoginAndRole();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    if (this.data.jobId) {
      this.loadJobInfo();
      this.loadApplicants(true);
    }
  },

  // 检查登录状态和用户角色
  checkLoginAndRole() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/profile/profile'
        });
      }, 1500);
      return;
    }

    if (userInfo && userInfo.role !== 'EMPLOYER') {
      wx.showToast({
        title: '仅限用工方使用',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    this.loadJobInfo();
    this.loadApplicants(true);
  },

  // 加载岗位信息
  loadJobInfo() {
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/api/employer/jobs/${this.data.jobId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({ jobInfo: res.data.data });
          wx.setNavigationBarTitle({
            title: `${res.data.data.title} - 申请者`
          });
        }
      },
      fail: () => {
        // 模拟数据
        const mockJob = {
          id: this.data.jobId,
          title: '餐厅服务员',
          location: '北京市朝阳区',
          salary: 25,
          salaryType: 'HOURLY',
          requiredWorkers: 5
        };
        this.setData({ jobInfo: mockJob });
        wx.setNavigationBarTitle({
          title: `${mockJob.title} - 申请者`
        });
      }
    });
  },

  // 加载申请者列表
  loadApplicants(refresh = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    const page = refresh ? 0 : this.data.page;
    const token = wx.getStorageSync('token');
    const status = this.data.tabs[this.data.activeTab].key;

    wx.request({
      url: `http://localhost:8080/api/employer/jobs/${this.data.jobId}/applications`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        page: page,
        size: this.data.size,
        status: status
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newApplicants = res.data.data.content || [];
          this.setData({
            applicants: refresh ? newApplicants : [...this.data.applicants, ...newApplicants],
            hasMore: !res.data.data.last,
            page: page + 1
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        // 模拟数据
        const mockApplicants = [
          {
            id: 1,
            applicantName: '张三',
            phone: '138****5678',
            idCard: '110101****1234',
            address: '北京市朝阳区',
            applicationReason: '我有相关工作经验，能够胜任这个岗位',
            status: 'PENDING',
            applyTime: '2024-01-10 14:30:00',
            workerProfile: {
              skills: '服务经验丰富',
              experience: '2年餐饮服务经验'
            }
          },
          {
            id: 2,
            applicantName: '李四',
            phone: '139****9876',
            idCard: '110102****5678',
            address: '北京市海淀区',
            applicationReason: '时间灵活，工作认真负责',
            status: 'APPROVED',
            applyTime: '2024-01-09 10:15:00',
            workerProfile: {
              skills: '沟通能力强',
              experience: '1年服务行业经验'
            }
          }
        ];

        this.setData({
          applicants: refresh ? mockApplicants : [...this.data.applicants, ...mockApplicants],
          hasMore: false,
          page: page + 1
        });
      },
      complete: () => {
        this.setData({ loading: false });
        if (refresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index,
      page: 0,
      applicants: []
    });
    this.loadApplicants(true);
  },

  // 查看申请者详情
  viewApplicantDetail(e) {
    const applicant = e.currentTarget.dataset.applicant;
    
    wx.showModal({
      title: '申请者详情',
      content: `姓名：${applicant.applicantName}\n手机：${applicant.phone}\n身份证：${applicant.idCard}\n地址：${applicant.address || '未填写'}\n申请理由：${applicant.applicationReason}`,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 通过申请
  approveApplication(e) {
    const applicationId = e.currentTarget.dataset.id;
    const applicantName = e.currentTarget.dataset.name;
    
    wx.showModal({
      title: '确认通过',
      content: `确定要通过 ${applicantName} 的申请吗？`,
      success: (res) => {
        if (res.confirm) {
          this.updateApplicationStatus(applicationId, 'APPROVED');
        }
      }
    });
  },

  // 拒绝申请
  rejectApplication(e) {
    const applicationId = e.currentTarget.dataset.id;
    const applicantName = e.currentTarget.dataset.name;
    
    wx.showModal({
      title: '确认拒绝',
      content: `确定要拒绝 ${applicantName} 的申请吗？`,
      success: (res) => {
        if (res.confirm) {
          this.updateApplicationStatus(applicationId, 'REJECTED');
        }
      }
    });
  },

  // 更新申请状态
  updateApplicationStatus(applicationId, status) {
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/api/employer/applications/${applicationId}/status`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: { status: status },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: status === 'APPROVED' ? '已通过申请' : '已拒绝申请',
            icon: 'success'
          });
          this.loadApplicants(true);
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: status === 'APPROVED' ? '已通过申请' : '已拒绝申请',
          icon: 'success'
        });
        this.loadApplicants(true);
      }
    });
  },

  // 联系申请者
  contactApplicant(e) {
    const phone = e.currentTarget.dataset.phone;
    
    wx.showModal({
      title: '联系申请者',
      content: `手机号：${phone}`,
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone.replace(/\*/g, ''),
            fail: () => {
              wx.showToast({
                title: '拨打失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 格式化状态文本
  getStatusText(status) {
    const statusMap = {
      'PENDING': '待处理',
      'APPROVED': '已通过',
      'REJECTED': '已拒绝',
      'WITHDRAWN': '已撤回'
    };
    return statusMap[status] || status;
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'PENDING': '#fa8c16',
      'APPROVED': '#52c41a',
      'REJECTED': '#f5222d',
      'WITHDRAWN': '#8c8c8c'
    };
    return colorMap[status] || '#8c8c8c';
  },

  // 格式化薪资显示
  formatSalary(job) {
    if (!job) return '';
    const { salary, salaryType } = job;
    let unit = '';
    switch (salaryType) {
      case 'HOURLY': unit = '/时'; break;
      case 'DAILY': unit = '/天'; break;
      case 'MONTHLY': unit = '/月'; break;
      default: unit = '';
    }
    return `${salary}元${unit}`;
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadApplicants(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadApplicants(false);
    }
  }
});
